package main

import (
	"log"

	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"tianlian-ttc/internal/app/api/handler"
	"tianlian-ttc/internal/app/api/service"
	"tianlian-ttc/internal/pkg/middleware"
	"tianlian-ttc/internal/pkg/udpserver"
)

func main() {
	// 初始化配置
	// Initialize configuration
	initConfig()

	// 启动UDP服务器
	// Start UDP server
	udpserver.StartServer()

	// 创建HTTP服务器
	// Create HTTP server
	r := gin.New()

	// 使用日志中间件
	// Use logging middleware
	r.Use(gin.Recovery())
	r.Use(middleware.Logger())

	// 注册路由
	// Register routes
	registerRoutes(r)

	// 启动HTTP服务器
	// Start HTTP server
	addr := viper.GetString("server.http.addr")
	if err := r.Run(addr); err != nil {
		log.Fatalf("Error starting HTTP server: %v", err)
	}
}

// initConfig initializes the configuration
func initConfig() {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("configs/")

	if err := viper.ReadInConfig(); err != nil {
		log.Fatalf("Error reading config file: %v", err)
	}
}

// registerRoutes registers the HTTP routes
func registerRoutes(r *gin.Engine) {
	// 创建控制命令处理器
	// Create control command handler
	controlHandler := handler.NewControlHandler()

	// 创建任务服务
	// Create task service
	taskService := service.NewTaskService(&service.TaskConfig{
		BaseURL:       viper.GetString("services.task.base_url"),
		SourceId:      viper.GetString("services.task.source_id"),
		DestinationId: viper.GetString("services.task.destination_id"),
	})

	// 创建任务处理器
	// Create task handler
	taskHandler := handler.NewTaskHandler(taskService)

	// 控制命令路由
	// Control command routes
	r.POST("/control", controlHandler.SendControlCommand)

	// 任务路由
	// Task routes
	r.POST("/out/station/task/apply", taskHandler.ApplyTask)
	r.POST("/out/station/task/cancel", taskHandler.CancelTask)
	r.POST("/out/station/task/idleArc/query", taskHandler.QueryIdleArc)
}
